package com.server;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

public class LoginCheck extends HttpServlet {
	/**
	 * 登录结果检测
	 * 接收userId，psw，imei
	 * 更新数据库，qrcode、times、date
	 * 返回:
	 * status:
	 * -1  <----> 请求错误
	 *  1  <----> 教师
	 *  2  <----> 学生
	 *  3  <----> 密码错误
	 *  4  <----> 没有次账号
	 *  5  <----> IMEI未登记
	 *  6  <----> IMEI不匹配
	 */
	private String userId;		//账号
	private String psw;			//密码
	private String imei;		//设备串号
	private int status;			//记录返回状态
	private final static int REQUSET_ERROR = -1;
	private final static int TEACHER = 1;
	private final static int STUDENT = 2;
	private final static int PSW_ERROR = 3;
	private final static int NOT_EXIST = 4;
	private final static int IMEI_NOT_REGISTED = 5;
	private final static int IMEI_ERROR = 6;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		userId = request.getParameter("id");
		psw = request.getParameter("psw");
		imei = request.getParameter("imei");

		if(userId != null && !userId.equals("") && psw != null && !psw.equals("")){
			DBTools db = new DBTools();
			String sqlT = "SELECT password FROM teachers WHERE tid = " + userId + " LIMIT 1";
			String sqlS = "SELECT password,IMEI FROM students WHERE sno = " + userId + " LIMIT 1";
			ResultSet rs = db.query(sqlT);
			try {
				//教师表有信息
				if (rs.next()) {
					if(psw.equals(rs.getString("password"))){
						System.out.println("teacher");
						status = TEACHER;
					}else{
						System.out.println("密码错误");
						status = PSW_ERROR;
					}
				}else{
					rs = db.query(sqlS);
					//学生表有信息
					if(rs.next()){
						if(psw.equals(rs.getString("password"))){
							if(rs.getString("IMEI") == null || rs.getString("IMEI").isEmpty()){
								System.out.println("IMEI_NOT_REGISTED");
								status = IMEI_NOT_REGISTED;
							}else if (imei.equals(rs.getString("IMEI"))) {
								System.out.println("student");
								status = STUDENT;
							}else{
								System.out.println("IMEI_ERROR");
								status = IMEI_ERROR;
							}
						}else{
							System.out.println("密码错误");
							status = PSW_ERROR;
						}
					}else{
						System.out.println("账号不存在");
						status = NOT_EXIST;
					}
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}finally {
				db.close();
			}
		}else{
			status = REQUSET_ERROR;
		}

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.write("" + status);
		out.flush();
		out.close();
	}


	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
